package com.longg.service.impl;

import com.longg.dao.ArticleDao;
import com.longg.dao.FavoriteDao;
import com.longg.model.Article;
import com.longg.model.Favorite;
import com.longg.service.IArticleService;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ArticleServiceImpl implements IArticleService {
    private ArticleDao articleDao = new ArticleDao();
    private FavoriteDao favoriteDao = new FavoriteDao();


    @Override
    public List<Map<String, Object>> findArticleByPage(int currentPage,String name) {
        return articleDao.findArticleByPage(currentPage,name);
    }

    @Override
    public long getCount(String name) {
        return articleDao.getCount(name);
    }

    @Override
    public List<Map<String, Object>> favouriteArticle(int id, int currentPage, String name) {
        return articleDao.favouriteArticle(id,currentPage,name);
    }

    @Override
    public long getFCount(int id, String name) {
        return articleDao.getFCount(id, name);
    }

    @Override
    public boolean addArticleticle(String uName, int id, String title, String content) {
        Article article = new Article();
        article.setTitle(title);
        article.setContent(content);
        article.setUserId(id);
        article.setPublishDate(new Date());
        article.setPublishUsername(uName);
        article.setBrowseCount(0);
        int save = articleDao.save(article);
        return save > 0;
    }

    @Override
    public Map<String,Object> getArticleByid(int aid) {
        return articleDao.findArticleDetail(aid);
    }

    @Override
    public boolean offFavorite(int aid,int uid) {
        Map<String,Object> params = new HashMap<>();
        params.put("u_id",uid);
        params.put("a_id",aid);
        Favorite favorite = favoriteDao.findByCols("and",params).get(0);
        int i = favoriteDao.deleteById(favorite.getId());
        return i > 0;
    }

    @Override
    public boolean onFavorite(int uid, int aid) {
        Favorite favorite = new Favorite();
        favorite.setAId(aid);
        favorite.setUId(uid);
        int save = favoriteDao.save(favorite);
        return save > 0;
    }

    @Override
    public boolean ifFavorite(int uid, int aid) {
        Map<String,Object> params = new HashMap<>();
        params.put("u_id",uid);
        params.put("a_id",aid);
        List<Favorite> list = favoriteDao.findByCols("and", params);
        return !list.isEmpty();
    }
}
